<?php

namespace pmvc\ioc;

use pmvc\util\ReflectionUtil;

/**
 * Utilities for working with objects that
 * implement the {@link Ordered} interface.
 */
class OrderUtil {

	/**
	 * Sorts all of the given objects according
	 * to the value returned by {@link #getOrder()}
	 * for each of them.
	 * @param Array $objects
	 */
	public static function sort(Array &$objects) {
		if (count($objects)==0) { return true; }
		return usort($objects, function($a, $b) {
			$i1 = OrderUtil::getOrder($a);
			$i2 = OrderUtil::getOrder($b);
			return ($i1 < $i2) ? -1 : ($i1 > $i2) ? 1 : 0;
		});
	}

	/**
	 * Returns the order of an object.  This method will
	 * return the value returned by {@link Ordered#getOrder()}
	 * if the object implements the {@link Ordered} interface.
	 * {@link Ordered::LOWEST_PRECEDENCE} is returned otherwise.
	 * @param mixed $obj
	 */
	public static function getOrder($obj) {
		return (ReflectionUtil::isInstance($obj, 'pmvc\ioc\Ordered'))
			? intval($obj->getOrder())
			: intval(Ordered::LOWEST_PRECEDENCE);
	}

}

?>